package com.anjufang.service.system.impl;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.anjufang.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.anjufang.entity.GroupDetail;
import com.anjufang.entity.GroupInfo;
import com.anjufang.entity.SourceUser;
import com.anjufang.mapper.GroupInfoMapper;
import com.anjufang.service.system.GroupInfoService;
import com.anjufang.utils.Result;
import com.anjufang.utils.page.Query;
import org.springframework.stereotype.Service;

@Service
public class GroupInfoServiceImpl implements GroupInfoService{
	
	@Autowired
	private GroupInfoMapper groupInfoMapper; 
	@Override
	public Result insert(String startTime, int longTime, int groupSize) throws Exception {
		
		//是否可以分组
		int p = new GroupDetail().selectCount("is_deleted = {0}", 0);
		if( p <= 0) { 
			//获取用户总数
			int number = 0; //分多少组
			int total = new SourceUser().selectCount("is_deleted = {0}", 0);
			int size = total / groupSize; 
			int size_ = total % groupSize;
			if( size_ > 0 ) {
				number = size + 1;
			} else {
				number = size;
			}
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date time = sdf.parse(startTime);
			groupInfoMapper.deleteAll();
			
			//重新分组
			for(int i = 1; i <= number; i++) {
				GroupInfo groupInfo_ = new GroupInfo();
				groupInfo_.setGroupName( i + ""); //分组名称
				groupInfo_.setBeginTime(time); //开始时间
				if(i == number) {
					groupInfo_.setGroupSize( total - ((number -1) * groupSize) );
				} else {
					groupInfo_.setGroupSize( groupSize );
				}
				
				long tempTime = time.getTime() + longTime * 60 * 1000; 
				time = new Date( tempTime );
				
				groupInfo_.setCreateTime(new Date());
				groupInfo_.setUpdateTime(new Date());
				groupInfo_.setIsDeleted(0);
				groupInfo_.insert();
			}
			
			return Result.ok();
		} else {
			return Result.error("分组内已有用户，不能重新分组");
		}
	}

	@Override
	public List<GroupInfo> queryList(Map<String, Object> map) {
		return groupInfoMapper.queryList(map);
	}

	@Override
	public int queryTotal(Query query) {
		return groupInfoMapper.queryTotal(query);
	}

	/**
	 * 编辑时间
	 * @param id
	 * @param startTime
	 * @param endTime
	 * @
	 */
	@Override
	public Result edit(Long id, String startTime, String endTime)throws Exception {
		if(StringUtils.isBlank(startTime)||StringUtils.isBlank(endTime)){
			return Result.error("参数不能为空");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		GroupInfo groupInfo = new GroupInfo();
		groupInfo.setId(id);
		GroupInfo groupInfo1 = groupInfo.selectById();
		Date time = sdf.parse(startTime);
		Date end = sdf.parse(endTime);
		groupInfo1.setBeginTime(time);
		groupInfo1.setEndTime(end);
		groupInfo1.updateById();
		return Result.ok();
	}

}
